<template>
  <div class="infoStatistics">
    <el-card class="box-card">
      <div class="card-header">
        <span>信息统计</span>
      </div>
      <el-cascader
        style="float: left"
        :options="options"
        :props="{ checkStrictly: true }"
        @change="getInfo"
      >
      </el-cascader>
      <el-select
        v-model="selectedClassname"
        placeholder="请选择课程"
        @change="getClassInfo"
      >
        <el-option
          v-for="item in classnameOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button class="dlButton" @click="dlTable" type="primary"
        >下载表格</el-button
      >
      <el-button class="addButton" @click="addScore" type="primary"
        >成绩录入</el-button
      >
      <el-table :data="StudentInfo" id="infoTable" :key="Math.random()">
        <el-table-column
          label="课程"
          prop="classname"
          v-if="visible1"
        ></el-table-column>
        <el-table-column
          label="姓名"
          prop="studentname"
          v-if="visible2"
        ></el-table-column>
        <el-table-column label="学号" prop="studentnumber"></el-table-column>
        <el-table-column label="成绩" prop="score"></el-table-column>
        <el-table-column label="等级" prop="grade"></el-table-column>
        <el-table-column label="学期" prop="xueqi"></el-table-column>
        <el-table-column prop="" v-if="buttonVisible">
          <template v-slot="scope">
            <el-button @click="showUpdateForm(scope.row)">修改</el-button>
            <el-button @click="deleteSc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="添加成绩" v-model="addVisible" width="30%">
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="addForm"
      >
        <el-form-item label="学号" class="item">
          <el-input v-model="addForm.studentnumber"></el-input>
        </el-form-item>
        <el-form-item label="课程名" class="item">
          <el-select
            size="medium"
            v-model="addForm.classname"
            placeholder="请选择课程"
          >
            <el-option
              v-for="item in classnameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" class="item">
          <el-input v-model="addForm.score" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <p>点击上传按钮上传文件，只能上传excel文件</p>
        <el-row>
          <el-col :span="12">
            <el-upload
              ref="upload"
              name="file"
              :auto-upload="true"
              :on-success="uploadSuccess"
              :on-error="uploadFalse"
              action="http://localhost:8081/user/fileimport"
              accept=".xlsx,.xls,.sql"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" @click="submitUpload">
                选取文件
              </el-button>
            </el-upload>
          </el-col>
          <el-col :span="12">
            <el-button size="small" @click="submitUpdate" type="primary"
              >提交</el-button
            >
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog title="修改成绩" v-model="updateVisible" width="30%">
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="updateForm"
      >
        <el-form-item label="分数" class="item">
          <el-input v-model="updateForm.score" type="number"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="updateScore()">修改</el-button>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import { path } from "../../config.json";
import { ElMessage } from "element-plus";
import XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
  name: "InfoStatistics",
  inject: ["reload"],
  data() {
    return {
      buttonVisible:true,
      visible1: true,
      visible2: false,
      addVisible: false,
      updateVisible: false,
      columnName: "课程",
      columnValue: [],
      StudentInfo: [],
      updateForm: {
        score: 0,
        studentnumber: 0,
        classname: "",
        studentname: "",
        xueqi: "",
      },
      options: [
        {
          value: "所有成绩",
          label: "所有成绩",
        },
        {
          value: "计算机",
          label: "计算机",
          children: [
            {
              value: "软件工程",
              label: "软件工程",
              children: [
                {
                  value: "1班",
                  label: "1班",
                },
                {
                  value: "2班",
                  label: "2班",
                },
              ],
            },
            {
              value: "信息安全",
              label: "信息安全",
              children: [
                {
                  value: "1班",
                  label: "1班",
                },
                {
                  value: "2班",
                  label: "2班",
                },
              ],
            },
            {
              value: "计算机科学与技术",
              label: "计算机科学与技术",
              children: [
                {
                  value: "1班",
                  label: "1班",
                },
                {
                  value: "2班",
                  label: "2班",
                },
              ],
            },
            {
              value: "网络工程",
              label: "网络工程",
              children: [
                {
                  value: "1班",
                  label: "1班",
                },
                {
                  value: "2班",
                  label: "2班",
                },
              ],
            },
          ],
        },
      ],
      selectValue: "所有成绩",
      allClass: [],
      classnameOptions: [],
      selectedClassname: "",
      addForm: {
        studentnumber: null,
        classname: "",
        score: null,
      },
    };
  },
  methods: {
    getInfo(xinxi) {
      if (xinxi[0] == "计算机") {
        this.StudentInfo = [];
        let department = xinxi[0];
        let major = xinxi[1];
        if (major == null) {
          major = "";
        }
        let classnumber = xinxi[2];
        this.selectValue = xinxi[0] + xinxi[1] + xinxi[2];
        if (classnumber == null) {
          classnumber = "";
        }
        axios({
          headers: {
            token: sessionStorage.getItem("token"), //此处放置请求到的用户token
          },
          method: "post",
          url: path + "/user/findScoreMap",
          data: {
            department: department,
            major: major,
            classnumber: classnumber,
          },
        }).then((response) => {
          this.StudentInfo = response.data;
        });
      } else {
        axios({
          headers: {
            token: sessionStorage.getItem("token"), //此处放置请求到的用户token
          },
          method: "post",
          url: path + "/Sc/findAllSc",
          data: {},
        }).then((response) => {
          this.StudentInfo = response.data;
        });
      }
      this.visible2 = false;
      this.visible1 = true;
    },
    dlTable() {
      this.buttonVisible = false;
      // 初始化
      var workbook = XLSX.utils.book_new();
      // 数据
      var ws1 = XLSX.utils.table_to_sheet(document.getElementById("infoTable"));
      // 这是  Sheet
      XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
      let fileName = "";
      if (this.visible1 == true) {
        fileName = this.selectValue;
      } else {
        fileName = this.selectedClassname;
      }
      XLSX.writeFile(workbook, fileName + ".xlsx");

      this.buttonVisible = true;
    },
    getClassNames() {
      //获取所有的课程名
      this.classNames = new Array();
      let allClassTemp = this.allClass;
      this.classnameOptions = new Array();
      for (let i in allClassTemp) {
        let temp = {
          value: allClassTemp[i].classname,
          label: allClassTemp[i].classname,
        };

        this.classnameOptions.push(temp);
      }
    },
    getClassInfo(classname) {
      axios({
        headers: {
          token: sessionStorage.getItem("token"), //此处放置请求到的用户token
        },
        method: "post",
        url: path + "/user/findScoreMapByClassName",
        data: {
          classname: classname,
        },
      }).then((res) => {
        this.StudentInfo = res.data;
      });
      this.visible2 = true;
      this.visible1 = false;
    },
    addScore() {
      this.addVisible = true;
      this.addForm = {};
    },
    submitUpdate() {
      let studentnumber = Number(this.addForm.studentnumber);
      let classname = this.addForm.classname;
      let score = Number(this.addForm.score);
      axios({
        headers: {
          token: sessionStorage.getItem("token"), //此处放置请求到的用户token
        },
        method: "post",
        url: path + "/Sc/insertSc",
        data: {
          studentnumber: studentnumber,
          classname: classname,
          score: score,
        },
      })
        .then((response) => {
          if (response.data === 1) {
            this.addVisible = false;
            ElMessage.success({
              message: "成绩添加成功",
              type: "success",
            });
          } else {
            this.addVisible = false;
            ElMessage.error({
              message: "成绩添加失败，请输入正确的信息",
              type: "error",
            });
          }
        })
        .catch(function (error) {
          this.addVisible = false;
          ElMessage.error("成绩添加失败，请输入正确的信息");
        });
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    uploadSuccess(response, file, fileList) {
      this.addVisible = false;
      ElMessage.success({
        message: "添加成功",
        type: "success",
      });
    },
    uploadFalse(response, file, fileList) {
      alert("文件上传失败！");
    },
    deleteSc(row) {
      axios({
        headers: {
          token: sessionStorage.getItem("token"), //此处放置请求到的用户token
        },
        method: "post",
        url: path + "/Sc/deleteSc",
        data: {
          studentnumber: row.studentnumber,
          classname: row.classname,
        },
      }).then((response) => {
        let data = response.data;
        if (data == 1) {
          ElMessage.success("删除成功！");
          if (this.visible1 == true) {
            axios({
              headers: {
                token: sessionStorage.getItem("token"), //此处放置请求到的用户token
              },
              method: "post",
              url: path + "/Sc/findAllSc",
              data: {},
            }).then((response) => {
              this.StudentInfo = response.data;
            });
          } else {
            this.getClassInfo(this.selectedClassname);
          }
        } else if (data == 0) {
          ElMessage.error("删除失败！");
        } else {
          ElMessage.error("与服务器通信失败！");
        }
      });
    },
    showUpdateForm(row) {
      this.updateForm = row;
      this.updateVisible = true;
    },
    updateScore() {
      axios({
        headers: {
          token: sessionStorage.getItem("token"), //此处放置请求到的用户token
        },
        method: "post",
        url: path + "/Sc/changeStudentScore",
        data: {
          studentnumber: this.updateForm.studentnumber,
          classname: this.updateForm.classname,
          score: this.updateForm.score,
          xueqi: this.updateForm.xueqi,
        },
      }).then((response) => {
        let data = response.data;
        if (data == 1) {
          ElMessage.success("修改成功！");
          if (this.visible1 == true) {
            axios({
              headers: {
                token: sessionStorage.getItem("token"), //此处放置请求到的用户token
              },
              method: "post",
              url: path + "/Sc/findAllSc",
              data: {},
            }).then((response) => {
              this.StudentInfo = response.data;
            });
          } else {
            this.getClassInfo(this.selectedClassname);
          }
          this.updateVisible = false;
        } else if (data == 0) {
          ElMessage.error("修改失败！");
        } else {
          ElMessage.error("与服务器通信失败！");
        }
      });
    },
  },
  async mounted() {
    axios({
      headers: {
        token: sessionStorage.getItem("token"), //此处放置请求到的用户token
      },
      method: "post",
      url: path + "/Sc/findAllSc",
      data: {},
    }).then((response) => {
      this.StudentInfo = response.data;
    });
    await axios({
      headers: {
        token: sessionStorage.getItem("token"), //此处放置请求到的用户token
      },
      method: "post",
      url: path + "/classTable/findAllClassTable",
      data: {},
    }).then((res) => {
      this.allClass = res.data;
    });
    this.getClassNames();
  },
};
</script>
<style  scoped>
.button {
  float: right;
}
.box-card {
  height: 90vh;
}
.option {
  float: left;
}
.passwordInput {
  width: 220px;
  float: left;
}
.dlButton {
  float: right;
}
.addButton {
  float: right;
  margin-right: 20px;
}
.item {
  width: 80%;
}
</style>